#!/bin/bash

# CentOS/RHEL 快速安装脚本
# 适用于您的服务器 82.157.51.127

set -e

# 配置变量
PROJECT_NAME="tetris-game"
PROJECT_DIR="/opt/jpom/projects/${PROJECT_NAME}"
WEBHOOK_PORT="9999"
APP_PORT="3000"
GIT_REPO="https://gitee.com/your-username/tetris-game.git"  # 请替换为您的仓库地址

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1"
}

error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1"
    exit 1
}

# 检查是否为 root 用户
if [ "$EUID" -ne 0 ]; then
    error "请使用 root 用户运行此脚本"
fi

log "🚀 开始配置 CentOS/RHEL 服务器环境..."

# 1. 检查系统版本
log "📋 检查系统信息..."
if [ -f /etc/redhat-release ]; then
    log "系统版本: $(cat /etc/redhat-release)"
else
    warn "无法确定系统版本，继续安装..."
fi

# 2. 更新系统
log "📦 更新系统包..."
yum update -y

# 3. 安装 EPEL 仓库
log "📦 安装 EPEL 仓库..."
yum install -y epel-release

# 4. 安装基础软件
log "🔧 安装基础软件..."
yum install -y \
    curl \
    wget \
    git \
    python3 \
    python3-pip \
    nginx \
    firewalld \
    net-tools \
    vim \
    htop

# 5. 安装 Docker
log "🐳 安装 Docker..."
if ! command -v docker &> /dev/null; then
    # 安装 Docker 官方仓库
    yum install -y yum-utils
    yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
    yum install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
else
    log "Docker 已安装，跳过..."
fi

# 6. 启动 Docker 服务
log "🐳 配置 Docker 服务..."
systemctl start docker
systemctl enable docker
usermod -aG docker $USER

# 7. 安装 Docker Compose (如果没有)
log "🐳 安装 Docker Compose..."
if ! command -v docker-compose &> /dev/null; then
    curl -L "https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
    ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
fi

# 8. 安装 Python 依赖
log "🐍 安装 Python 依赖..."
pip3 install flask

# 9. 创建项目目录
log "📁 创建项目目录..."
mkdir -p "${PROJECT_DIR}"
mkdir -p /var/log

# 10. 克隆项目代码
log "📥 克隆项目代码..."
cd "${PROJECT_DIR}"
if [ -d ".git" ]; then
    log "更新现有仓库..."
    git pull origin main
else
    log "克隆新仓库..."
    git clone "${GIT_REPO}" .
fi

# 11. 配置权限
log "🔐 配置文件权限..."
chmod +x jpom-build.sh
chmod +x webhook-receiver.py
chmod +x server-setup.sh

# 12. 配置防火墙
log "🔥 配置防火墙..."
systemctl start firewalld
systemctl enable firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-port=${WEBHOOK_PORT}/tcp
firewall-cmd --permanent --add-port=${APP_PORT}/tcp
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

# 13. 配置 Nginx
log "🌐 配置 Nginx..."
systemctl start nginx
systemctl enable nginx

# 备份原配置
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup

# 创建项目配置
cat > /etc/nginx/conf.d/tetris-webhook.conf << 'EOF'
server {
    listen 80;
    server_name _;
    
    # Webhook 接收器
    location /webhook/ {
        proxy_pass http://127.0.0.1:9999;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    # 游戏应用
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    # 健康检查
    location /health {
        proxy_pass http://127.0.0.1:9999/health;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
EOF

# 测试 Nginx 配置
nginx -t && systemctl reload nginx

# 14. 配置 Webhook 服务
log "⚙️ 配置 Webhook 服务..."
cp webhook-receiver.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable webhook-receiver
systemctl start webhook-receiver

# 15. 配置 SELinux (如果启用)
log "🔒 配置 SELinux..."
if command -v getenforce >/dev/null 2>&1; then
    if [ "$(getenforce)" = "Enforcing" ]; then
        log "配置 SELinux 策略..."
        setsebool -P httpd_can_network_connect 1
        setsebool -P httpd_can_network_relay 1
    fi
fi

# 16. 等待服务启动
log "⏳ 等待服务启动..."
sleep 5

# 17. 检查服务状态
log "📊 检查服务状态..."
echo ""
echo "=== 服务状态检查 ==="
systemctl is-active docker && echo "✅ Docker: 运行中" || echo "❌ Docker: 未运行"
systemctl is-active nginx && echo "✅ Nginx: 运行中" || echo "❌ Nginx: 未运行"
systemctl is-active webhook-receiver && echo "✅ Webhook: 运行中" || echo "❌ Webhook: 未运行"
systemctl is-active firewalld && echo "✅ 防火墙: 运行中" || echo "❌ 防火墙: 未运行"

# 18. 显示配置信息
echo ""
log "✅ 服务器配置完成！"
echo ""
echo "📋 配置信息:"
echo "  服务器IP: 82.157.51.127"
echo "  项目目录: ${PROJECT_DIR}"
echo "  Webhook端口: ${WEBHOOK_PORT}"
echo "  应用端口: ${APP_PORT}"
echo ""
echo "🌐 访问地址:"
echo "  游戏应用: http://82.157.51.127"
echo "  健康检查: http://82.157.51.127/health"
echo "  Webhook URL: http://82.157.51.127/webhook/gitee"
echo ""
echo "🔧 下一步操作:"
echo "1. 在 Gitee 仓库中配置 Webhook: http://82.157.51.127/webhook/gitee"
echo "2. 推送代码测试自动部署"
echo "3. 手动构建测试: cd ${PROJECT_DIR} && ./jpom-build.sh"
echo ""
echo "📝 查看日志:"
echo "  Webhook 日志: tail -f /var/log/webhook-receiver.log"
echo "  Nginx 日志: tail -f /var/log/nginx/error.log"
echo "  Docker 日志: docker logs tetris-game"
echo ""
echo "🎉 环境配置完成！准备享受自动化部署吧！"
